package net.hserver.sync.task;

import cn.hserver.core.interfaces.TaskJob;
import cn.hserver.core.ioc.IocUtil;
import cn.hserver.core.queue.HServerQueue;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.github.sardine.DavResource;
import lombok.extern.slf4j.Slf4j;
import net.hserver.sync.config.EventConst;
import net.hserver.sync.config.FileState;
import net.hserver.sync.driver.WebDavDriver;
import net.hserver.sync.entity.SyncWebDavConfigEntity;
import net.hserver.sync.util.PathUtil;

import java.io.File;
import java.util.List;

@Slf4j
public class TaskRemoteLocal implements TaskJob {

    public void copyMode(SyncWebDavConfigEntity arg) {
        WebDavDriver driver = IocUtil.getBean(arg.getId(), WebDavDriver.class);
        List<DavResource> remoteFiles = driver.list(arg.getRootRemotePath(), -1);
        for (DavResource davResource : remoteFiles) {
            try {
                if (davResource.isDirectory()) {
                    continue;
                }
                String localPath = arg.remoteToLocalPath(davResource.getPath());
                File file = new File(localPath);
                if (!file.exists() || davResource.getContentLength()!=file.length()) {
                    HServerQueue.sendQueue(EventConst.REMOTE_CHANGE_EVENT, arg.getId(),FileState.onFileCreate, davResource.getPath(), file.getAbsolutePath());
                    log.info("下载文件：{}->{}", davResource.getPath(), file.getAbsolutePath());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    public void syncMode(SyncWebDavConfigEntity arg) {
        WebDavDriver driver = IocUtil.getBean(arg.getId(), WebDavDriver.class);
        //获取本地文件列表
        List<File> files = FileUtil.loopFiles(arg.getLocalPath());
        //获取远端文件列表
        List<DavResource> remoteFiles = driver.list(arg.getRootRemotePath(), -1);
        for (File localFile : files) {
            boolean exist = false;
            for (DavResource remoteFile : remoteFiles) {
                String local = arg.localToPath(localFile.getAbsolutePath());
                String remote = arg.remoteToPath(remoteFile.getPath());
                if (local.equals(remote)) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                log.info("删除文件：{}",localFile.getAbsolutePath());
                HServerQueue.sendQueue(EventConst.REMOTE_CHANGE_EVENT, arg.getId(), FileState.onFileDelete, "", localFile.getAbsolutePath());
            }
        }
        copyMode(arg);
    }


    @Override
    public void exec(Object... args) {
        SyncWebDavConfigEntity arg = (SyncWebDavConfigEntity) args[0];
        if (arg.getSyncMode() == SyncWebDavConfigEntity.SyncMode.copy) {
            copyMode(arg);
        } else {
            syncMode(arg);
        }
        log.info(JSONUtil.toJsonStr(arg));
    }
}
